<template>
  <div class="suspected-assets-management">
    <!-- 全局统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">📊 疑似资产统计</h2>
      <div class="stats-container">
        <StatisticCard
          label="总计"
          :value="stats.total.toString()"
          icon="el-icon-document"
          type="primary"
        />
        <StatisticCard
          label="待推理"
          :value="stats.pending.toString()"
          icon="el-icon-time"
          type="info"
        />
        <StatisticCard
          label="已推理"
          :value="stats.inferred.toString()"
          icon="el-icon-cpu"
          type="warning"
        />
        <StatisticCard
          label="已确认"
          :value="stats.confirmed.toString()"
          icon="el-icon-check"
          type="success"
        />
        <StatisticCard
          label="已拒绝"
          :value="stats.rejected.toString()"
          icon="el-icon-close"
          type="danger"
        />
        <StatisticCard
          label="已加白"
          :value="stats.whitelisted.toString()"
          icon="el-icon-finished"
          type="success"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div v-if="isFilterExpanded" class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 疑似资产列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div class="list-header">
        <div class="header-left">
          <el-button
            type="primary"
            :disabled="selectedIds.length === 0"
            @click="handleBatchInfer"
            style="margin-left: 15px"
          >
            批量推理 ({{ selectedIds.length }})
          </el-button>
          <el-button
            type="warning"
            :disabled="selectedIds.length === 0"
            @click="handleBatchCreateAlert"
            style="margin-left: 10px"
          >
            批量创建告警 ({{ selectedIds.length }})
          </el-button>
        </div>
        <div class="header-right">
          <span class="sort-label">排序:</span>
          <el-select
            v-model="filterForm.sort_by"
            size="small"
            style="width: 140px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="按置信度" value="confidence" />
            <el-option label="按创建时间" value="created_time" />
            <el-option label="按最后检测" value="last_detected" />
          </el-select>
          <el-select
            v-model="filterForm.sort_order"
            size="small"
            style="width: 80px"
            @change="handleSearch"
          >
            <el-option label="升序" value="asc" />
            <el-option label="降序" value="desc" />
          </el-select>
        </div>
      </div>

      <div v-loading="loading" class="table-wrapper">
        <DynamicTable
          :data="assetList"
          :columns="tableColumns"
          :loading="false"
          border
          row-key="id"
          selection-type="multiple"
          @selection-change="handleSelectionChange"
        >
          <template #inference_status="{ row }">
            <el-tag :type="getStatusType(row.inference_status)" size="small">
              {{ row.inference_status_name }}
            </el-tag>
          </template>

          <template #primary_department="{ row }">
            <div v-if="row.primary_department">
              <div class="department-name">{{ row.primary_department }}</div>
              <div class="confidence-value">
                置信度: {{ row.primary_confidence }}%
              </div>
            </div>
            <span v-else class="no-data">-</span>
          </template>

          <template #is_high_risk="{ row }">
            <el-tag v-if="row.is_high_risk" type="danger" size="small">
              高危
            </el-tag>
            <span v-else class="no-risk">-</span>
          </template>

          <template #alert_status="{ row }">
            <div v-if="row.alert_info && row.alert_info.has_alert">
              <el-tag type="warning" size="small"> 已告警 </el-tag>
              <div
                class="alert-detail"
                style="font-size: 12px; color: #909399; margin-top: 4px"
              >
                ID: {{ row.alert_info.alert_id }}
              </div>
            </div>
            <span v-else class="no-data">-</span>
          </template>

          <template #action="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                :disabled="row.inference_status === 'pending'"
                @click="handleViewDetail(row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="info"
                @click="handleViewProfileGraph(row)"
              >
                资产画像
              </el-button>
              <el-button
                v-if="row.inference_status === 'inferred'"
                size="small"
                type="success"
                @click="handleConfirm(row)"
              >
                确认
              </el-button>
              <el-button
                v-if="row.inference_status === 'inferred'"
                size="small"
                type="warning"
                @click="handleReject(row)"
              >
                驳回
              </el-button>
              <el-button
                v-if="row.alert_info && row.alert_info.has_alert"
                size="small"
                type="warning"
                @click="handleViewAlert(row)"
              >
                查看告警
              </el-button>
            </div>
          </template>
        </DynamicTable>

        <el-empty
          v-if="!loading && assetList.length === 0"
          description="暂无疑似资产数据"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pagination.total > 0">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes"
          :total="pagination.total"
          :layout="pagination.layout"
          :background="pagination.background"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 批量推理弹窗 -->
    <BatchInferModal
      v-model="batchInferVisible"
      :selected-ids="selectedIds"
      @refresh="handleRefresh"
    />

    <!-- 批量创建告警弹窗 -->
    <BatchCreateAlertModal
      v-model="batchCreateAlertVisible"
      :selected-ids="selectedIds"
      @refresh="handleRefresh"
    />

    <!-- 推理详情弹窗 -->
    <DetailModal v-model="detailVisible" :asset-id="currentAssetId" />

    <!-- 告警详情弹窗 -->
    <AlertDetailModal
      v-model="alertDetailVisible"
      :asset-id="currentAlertAssetId"
    />

    <!-- 确认弹窗 -->
    <ConfirmModal
      v-model="confirmVisible"
      :asset-id="currentConfirmAssetId"
      :department="currentConfirmDepartment"
      @confirm="handleConfirmSuccess"
    />

    <!-- 驳回弹窗 -->
    <RejectModal
      v-model="rejectVisible"
      :asset-id="currentRejectAssetId"
      :department="currentRejectDepartment"
      @reject="handleRejectSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import { querySuspectedAssets, batchQueryAlertStatus } from "../../servers";
import BatchInferModal from "./components/BatchInferModal.vue";
import BatchCreateAlertModal from "./components/BatchCreateAlertModal.vue";
import DetailModal from "./components/DetailModal.vue";
import AlertDetailModal from "./components/AlertDetailModal.vue";
import ConfirmModal from "./components/ConfirmModal.vue";
import RejectModal from "./components/RejectModal.vue";

const route = useRoute();
const router = useRouter();

// 页面状态
const isFilterExpanded = ref(true);
const loading = ref(false);
const batchInferVisible = ref(false);
const batchCreateAlertVisible = ref(false);
const selectedIds = ref<number[]>([]);
const detailVisible = ref(false);
const alertDetailVisible = ref(false);
const currentAssetId = ref<number | null>(null);
const currentAlertAssetId = ref<number | null>(null);
const confirmVisible = ref(false);
const rejectVisible = ref(false);
const currentConfirmAssetId = ref<number | null>(null);
const currentRejectAssetId = ref<number | null>(null);
const currentConfirmDepartment = ref<string>("");
const currentRejectDepartment = ref<string>("");

// 统计信息
const stats = reactive({
  total: 0,
  pending: 0,
  inferred: 0,
  confirmed: 0,
  rejected: 0,
  whitelisted: 0,
});

// 疑似资产列表数据
const assetList = ref<Array<any>>([]);

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  task: (route.query.task as string) || "",
  status: "",
  ip_version: "",
  confidence_min: "",
  confidence_max: "",
  is_high_risk: null as boolean | null,
  keyword: "",
  sort_by: "confidence",
  sort_order: "desc",
});

// 筛选表单配置
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "task",
    name: "所属任务",
    type: "input",
    placeholder: "请输入任务ID",
    col: { span: 6 },
  },
  {
    key: "status",
    name: "推理状态",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "待推理", value: "pending" },
      { label: "已推理", value: "inferred" },
      { label: "已确认", value: "confirmed" },
      { label: "已拒绝", value: "rejected" },
      { label: "已加白", value: "whitelisted" },
    ],
    col: { span: 6 },
  },
  {
    key: "ip_version",
    name: "IP版本",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "IPv4", value: "4" },
      { label: "IPv6", value: "6" },
    ],
    col: { span: 6 },
  },
  {
    key: "is_high_risk",
    name: "是否高危",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: null },
      { label: "是", value: true },
      { label: "否", value: false },
    ],
    col: { span: 6 },
  },
  {
    key: "keyword",
    name: "关键词搜索",
    type: "input",
    placeholder: "请输入IP/端口/标题关键词",
    col: { span: 6 },
  },
  // {
  //   key: "confidence_min",
  //   name: "最低置信度",
  //   type: "number",
  //   placeholder: "0",
  //   params: { min: 0, max: 100 },
  //   col: { span: 6 },
  // },
  // {
  //   key: "confidence_max",
  //   name: "最高置信度",
  //   type: "number",
  //   placeholder: "100",
  //   params: { min: 0, max: 100 },
  //   col: { span: 6 },
  // },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "疑似ID",
    prop: "suspected_id",
    minWidth: 150,
    fixed: "left",
  },
  {
    label: "资产IP",
    prop: "asset_ip",
    minWidth: 140,
  },
  {
    label: "端口",
    prop: "asset_port",
    minWidth: 80,
    align: "center",
  },
  {
    label: "服务类型",
    prop: "service_type",
    minWidth: 100,
    align: "center",
  },
  {
    label: "资产标题",
    prop: "asset_title",
    minWidth: 200,
    showOverflowTooltip: true,
  },
  {
    label: "推理状态",
    prop: "inference_status",
    minWidth: 100,
    align: "center",
    slot: "inference_status",
  },
  {
    label: "最佳推理部门",
    prop: "primary_department",
    minWidth: 250,
    slot: "primary_department",
  },
  {
    label: "首次检测",
    prop: "first_detected",
    minWidth: 160,
  },
  {
    label: "最后检测",
    prop: "last_detected",
    minWidth: 160,
  },
  {
    label: "是否高危",
    prop: "is_high_risk",
    minWidth: 100,
    align: "center",
    slot: "is_high_risk",
  },
  {
    label: "告警状态",
    prop: "alert_status",
    minWidth: 120,
    align: "center",
    slot: "alert_status",
  },
  {
    label: "来源任务",
    prop: "source_scan_task",
    minWidth: 150,
  },
  {
    label: "操作",
    width: 400,
    fixed: "right",
    slot: "action",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取状态标签类型
const getStatusType = (
  status: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    pending: "info",
    inferred: "warning",
    confirmed: "success",
    rejected: "danger",
    whitelisted: "success",
  };
  return typeMap[status] || "info";
};

// 获取疑似资产列表
const fetchAssetList = async (values?: any) => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
      ...values,
    };

    // 处理筛选参数
    if (filterForm.task) {
      params.task = filterForm.task;
    }
    if (filterForm.status) {
      params.status = filterForm.status;
    }
    if (filterForm.ip_version) {
      params.ip_version = Number(filterForm.ip_version) as 4 | 6;
    }
    if (filterForm.confidence_min !== "") {
      params.confidence_min = Number(filterForm.confidence_min);
    }
    if (filterForm.confidence_max !== "") {
      params.confidence_max = Number(filterForm.confidence_max);
    }
    if (filterForm.is_high_risk !== null) {
      params.is_high_risk = filterForm.is_high_risk;
    }
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }

    const { data } = await querySuspectedAssets(params);

    if (data) {
      // 更新统计信息
      if (data.stats) {
        stats.total = data.stats.total || 0;
        stats.pending = data.stats.pending || 0;
        stats.inferred = data.stats.inferred || 0;
        stats.confirmed = data.stats.confirmed || 0;
        stats.rejected = data.stats.rejected || 0;
        stats.whitelisted = data.stats.whitelisted || 0;
      }

      // 更新列表数据
      if (data.items && Array.isArray(data.items)) {
        assetList.value = data.items;

        // 批量查询告警状态
        if (data.items.length > 0) {
          await fetchAlertStatus(data.items.map((item: any) => item.id));
        }
      }

      // 更新分页信息
      if (data.pagination) {
        pagination.total = data.pagination.total || 0;
        pagination.currentPage = data.pagination.page || 1;
        pagination.pageSize = data.pagination.page_size || 20;
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取疑似资产列表失败");
  } finally {
    loading.value = false;
  }
};

// 批量查询告警状态
const fetchAlertStatus = async (assetIds: number[]) => {
  if (assetIds.length === 0) return;

  try {
    // 分批查询，每批最多100个
    const batchSize = 100;
    const batches: number[][] = [];
    for (let i = 0; i < assetIds.length; i += batchSize) {
      batches.push(assetIds.slice(i, i + batchSize));
    }

    // 并行查询所有批次
    const promises = batches.map((batch) =>
      batchQueryAlertStatus({ suspected_asset_ids: batch })
    );
    const results = await Promise.all(promises);

    // 合并结果并更新到列表中
    const alertStatusMap = new Map<number, any>();
    results.forEach((result) => {
      if (result.data && Array.isArray(result.data)) {
        result.data.forEach((item: any) => {
          alertStatusMap.set(item.suspected_asset_id, item);
        });
      }
    });

    // 更新列表中的告警信息
    assetList.value = assetList.value.map((item: any) => {
      const alertInfo = alertStatusMap.get(item.id);
      if (alertInfo) {
        return {
          ...item,
          alert_info: alertInfo,
        };
      }
      return item;
    });
  } catch (error: any) {
    // 告警状态查询失败不影响主流程，只记录错误
    console.error("查询告警状态失败:", error);
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.task = (route.query.task as string) || "";
  filterForm.status = "";
  filterForm.ip_version = "";
  filterForm.confidence_min = "";
  filterForm.confidence_max = "";
  filterForm.is_high_risk = null;
  filterForm.keyword = "";
  filterForm.sort_by = "confidence";
  filterForm.sort_order = "desc";
  pagination.currentPage = 1;
  fetchAssetList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchAssetList(values);
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchAssetList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchAssetList();
};

// 查看详情
const handleViewDetail = (row: any) => {
  // 只有推理过的才能查看详情
  if (row.inference_status === "pending") {
    ElMessage.warning("该资产尚未推理，无法查看详情");
    return;
  }

  if (row.id) {
    currentAssetId.value = row.id;
    detailVisible.value = true;
  } else {
    ElMessage.warning("资产ID不存在");
  }
};

// 查看资产画像图谱
const handleViewProfileGraph = (row: any) => {
  if (row.id) {
    router.push({
      name: "assetProfileGraph",
      params: {
        asset_id: row.id,
      },
    });
  } else {
    ElMessage.warning("资产ID不存在");
  }
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map((item) => item.id);
};

// 批量推理
const handleBatchInfer = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要推理的资产");
    return;
  }
  batchInferVisible.value = true;
};

// 批量创建告警
const handleBatchCreateAlert = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要创建告警的资产");
    return;
  }
  if (selectedIds.value.length > 100) {
    ElMessage.warning("单次最多支持100个资产");
    return;
  }
  batchCreateAlertVisible.value = true;
};

// 刷新列表
const handleRefresh = () => {
  selectedIds.value = [];
  fetchAssetList();
};

// 确认推理结果
const handleConfirm = (row: any) => {
  if (row.inference_status !== "inferred") {
    ElMessage.warning("只有已推理状态才能确认");
    return;
  }
  currentConfirmAssetId.value = row.id;
  currentConfirmDepartment.value = row.primary_department || "";
  confirmVisible.value = true;
};

// 驳回推理结果
const handleReject = (row: any) => {
  if (row.inference_status !== "inferred") {
    ElMessage.warning("只有已推理状态才能驳回");
    return;
  }
  currentRejectAssetId.value = row.id;
  currentRejectDepartment.value = row.primary_department || "";
  rejectVisible.value = true;
};

// 确认成功
const handleConfirmSuccess = () => {
  fetchAssetList();
};

// 驳回成功
const handleRejectSuccess = () => {
  fetchAssetList();
};

// 查看告警详情
const handleViewAlert = (row: any) => {
  if (row.id) {
    currentAlertAssetId.value = row.id;
    alertDetailVisible.value = true;
  } else {
    ElMessage.warning("资产ID不存在");
  }
};

// 初始化
onMounted(() => {
  fetchAssetList();
});
</script>

<style scoped lang="scss">
.suspected-assets-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-card,
  .filter-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-content {
    padding: 5px 0;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .list-title {
      font-size: 16px;
      font-weight: 500;
      margin: 0;
      color: #303133;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 10px;

      .sort-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .table-wrapper {
    min-height: 200px;
  }

  .department-name {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }

  .confidence-value {
    font-size: 12px;
    color: #909399;
  }

  .no-data,
  .no-risk {
    color: #909399;
    font-size: 12px;
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
}
</style>
